#pragma once
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <vector>
#include <string>
#include <iostream>
#include "Task.hpp"
#define INIT_CHANNEL_NUM 5
// 管道（先组织）
class Channel
{
public:
    Channel(int fd, pid_t id) : _wfd(fd), _subid(id)
    {
        _name = "channel - " + std::to_string(_wfd) + " - " + std::to_string(id);
    }
    ~Channel()
    {
    }
    void Send(int code)
    {
        ssize_t ret = write(_wfd, &code, sizeof(code));
        (void)ret;
    }
    int FD() { return _wfd; }
    pid_t ID() { return _subid; }
    std::string Name() { return _name; }
    void Close()
    {
        close(_wfd);
    }
    void Wait()
    {
        int rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }

private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};
// 管道管理 （在管理）
class ChannelManager
{
public:
    ChannelManager() : _next(0)
    {
    }
    void InsertChannel(int wfd, int subpid)
    {
        _channels.emplace_back(wfd, subpid);
    }
    ~ChannelManager()
    {
    }
    void PrintChannel()
    {
        for (auto &channel : _channels)
        {
            std::cout << channel.Name() << std::endl;
        }
    }
    Channel &Select()
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }
    void StopSubProcess()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭: " << channel.Name() << std::endl;
        }
    }
    void WaitSubProcess()
    {
        for (auto &channel : _channels)
        {
            channel.Wait();
            std::cout << "回收: " << channel.Name() << std::endl;
        }
    }
    void CloseAndWait()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭: " << channel.Name() << std::endl;
            channel.Wait();
            std::cout << "回收: " << channel.Name() << std::endl;
        }
    }
    void CloseByReverse()
    {
        for (int i = _channels.size() - 1; i >= 0; i--)
        {
            _channels[i].Close();
            std::cout << "关闭: " << _channels[i].Name() << std::endl;
            _channels[i].Wait();
            std::cout << "回收: " << _channels[i].Name() << std::endl;
        }
    }
    void CloseAll()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
        }
    }

private:
    std::vector<Channel> _channels;
    int _next;
};
class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num)
    {
        _tm.Insert(Register);
        _tm.Insert(DownLoad);
        _tm.Insert(LoadData);
    }
    void Work(int rfd)
    {
        while (true)
        {
            // 读取父进程提供的执行码
            int code = 0;
            int n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    continue;
                }
                // 执行执行码的任务
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取错误" << std::endl;
                break;
            }
        }
    }
    void debug()
    {
        _cm.PrintChannel();
    }

    bool Start()
    {
        for (int i = 0; i < _process_num; i++)
        {
            // 1. 创建管道
            int fds[2] = {0};
            int fd = pipe(fds);
            // 2. 创建子进程
            pid_t subid = fork();
            if (subid > 0)
            {
                sleep(1);
                // 父进程
                // 关闭读，只写
                close(fds[0]);
                // 到管道处理
                _cm.InsertChannel(fds[1], subid);
            }
            else if (subid == 0)
            {
                // 子进程
                // 关闭写，只读
                // 需要关闭哥哥的w端
                std::cout << "##########" << "第" << i << "次" << std::endl;
                _cm.PrintChannel();
                std::cout << "##########" << std::endl;
                _cm.CloseAll();
                // 关闭不需要的文件描述符
                close(fds[1]);
                Work(fds[0]); //  读取数据
                close(fds[0]);
                exit(0);
            }
            else
            {
                return false;
            }
        }
        return true;
    }
    void Run()
    {
        // 选择一个任务
        int taskcode = _tm.Code();
        auto &channel = _cm.Select();
        std::cout << "选择了一个子进程: " << channel.Name() << std::endl;
        // 2. 发送任务
        channel.Send(taskcode);
        std::cout << "发送了一个任务码: " << taskcode << std::endl;
    }
    ~ProcessPool()
    {
    }
    void Stop()
    {
        // _cm.StopSubProcess();
        // _cm.WaitSubProcess();
        _cm.CloseAndWait();
        // _cm.CloseByReverse();
    }

private:
    ChannelManager _cm;
    int _process_num;
    TaskManager _tm;
};
